# 请确保已安装pygame库，可以通过运行`pip install pygame`来安装。
import random

import pygame
import sys
from food import Food
from snake import Snake, AISnake  # 导入AISnake类
from particle import Particle

# 初始化pygame
pygame.init()
# 设置窗口大小（假设通过硬编码的方式设置）
WIDTH, HEIGHT = 800, 600  # 这里可以替换为从用户输入或其他方式获取的值
AI_RESPAWN_TIME = 3000

# 设置游戏时钟
clock = pygame.time.Clock()

# 加载音效
pygame.mixer.init()
collision_sound = pygame.mixer.Sound("collision.mp3")  # 预加载音效文件
click_sound = pygame.mixer.Sound("click.mp3")  # 预加载点击音效文件
bgm = pygame.mixer.Sound("BGM.mp3")  # 预加载背景音乐文件
eat_sound = pygame.mixer.Sound("eat.mp3")  # 预加载吃到食物音效文件

# 设置字体
font = pygame.font.Font(None, 36)

# 创建屏幕对象
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

# 初始化游戏元素
game_area_width = int(WIDTH * 0.8)  # 左侧80%的游戏区域宽度
game_area_height = HEIGHT  # 整个窗口的高度
snake = Snake(game_area_width, game_area_height)
ai_snake = AISnake(game_area_width, game_area_height)  # 传递snake对象作为参数
food_list = [Food(WIDTH, HEIGHT) for _ in range(5)]  # 初始化5个食物对象
particles = []
explosion_active = False
explosion_timer = 0
food_timer = 0
FOOD_RESPAWN_TIME = 60  # 食物重生时间（帧数）

def reset():
    global snake, ai_snake, food_list, particles, explosion_active, explosion_timer, food_timer
    snake = Snake(game_area_width, game_area_height)
    ai_snake = AISnake(game_area_width, game_area_height)  # 传递snake对象作为参数
    food_list = [Food(WIDTH, HEIGHT) for _ in range(5)]  # 重置食物对象
    particles = []
    explosion_active = False
    explosion_timer = 0
    food_timer = 0
    bgm.stop()
    bgm.play(-1)  # 重新开始播放背景音乐

def draw_background():
    # 左侧80%的游戏区域背景为灰色
    pygame.draw.rect(screen, (128, 128, 128), (0, 0, game_area_width, game_area_height))
    # 右侧20%的得分显示区域背景为白色
    pygame.draw.rect(screen, (255, 255, 255), (game_area_width, 0, WIDTH - game_area_width, game_area_height))
    # 绘制白色分割线
    pygame.draw.line(screen, (255, 255, 255), (game_area_width, 0), (game_area_width, HEIGHT), 2)

def draw_snake():
    for segment in snake.body:
        pygame.draw.circle(screen, (0, 255, 0), (segment[0] + 10, segment[1] + 10), 10)

def draw_ai_snake():
    for segment in ai_snake.body:
        pygame.draw.circle(screen, (255, 0, 0), (segment[0] + 10, segment[1] + 10), 10)

def draw_food():
    for food in food_list:
        pygame.draw.circle(screen, food.color, (food.position[0] + 10, food.position[1] + 10), 10)


def draw_particles():
    for particle in particles:
        particle.draw(screen)


def draw_score():
    score_text = font.render(f"Score: {len(snake.body)}", True, (0, 0, 0))
    screen.blit(score_text, (game_area_width + 10, 10))

def draw_game_over():
    game_over_text = font.render("Game Over", True, (255, 255, 255))
    score_text = font.render(f"Score: {len(snake.body)}", True, (255, 255, 255))
    restart_button = pygame.Rect(WIDTH // 2 - 60, HEIGHT // 2, 120, 40)
    quit_button = pygame.Rect(WIDTH // 2 - 60, HEIGHT // 2 + 60, 120, 40)

    screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2 - 100))
    screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 - 50))
    pygame.draw.rect(screen, (0, 128, 0), restart_button)
    pygame.draw.rect(screen, (255, 0, 0), quit_button)
    screen.blit(font.render("Restart", True, (255, 255, 255)), (WIDTH // 2 - 30, HEIGHT // 2 + 10))
    screen.blit(font.render("Quit", True, (255, 255, 255)), (WIDTH // 2 - 20, HEIGHT // 2 + 70))


def explosion():
    # 生成爆炸粒子
    for _ in range(50):  # 生成50个粒子
        particles.append(Particle(snake.body[0][0], snake.body[0][1], random.randint(0, 360)))
    collision_sound.play()  # 播放碰撞音效

def update_food():
    global food_timer
    food_timer += 1
    if food_timer >= FOOD_RESPAWN_TIME:
        food_timer = 0
        for food in food_list:
            if food.position in snake.body or food.position in ai_snake.body:
                food.reset()

def check_food_collision(snake_head, food_positions):
    for food_pos in food_positions:
        distance = ((snake_head[0] - food_pos[0]) ** 2 + (snake_head[1] - food_pos[1]) ** 2) ** 0.5
        if distance < 20:  # 假设蛇头与食物的距离小于20像素时认为吃到食物
            return food_pos
    return None

reset()

# 游戏主循环
running = True
ai_respawn_timer = 0
game_state = "playing"  # 初始化游戏状态为"playing"
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if game_state == "playing" and not explosion_active:
                if event.key == pygame.K_UP and snake.acceleration != [0, -1]:
                    snake.change_direction([0, -1])
                elif event.key == pygame.K_DOWN and snake.acceleration != [0, 1]:
                    snake.change_direction([0, 1])
                elif event.key == pygame.K_LEFT and snake.acceleration != [-1, 0]:
                    snake.change_direction([-1, 0])
                elif event.key == pygame.K_RIGHT and snake.acceleration != [1, 0]:
                    snake.change_direction([1, 0])
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if game_state == "game_over" and not explosion_active:
                click_sound.play()  # 播放点击音效
                mouse_pos = pygame.mouse.get_pos()
                restart_button = pygame.Rect(WIDTH // 2 - 60, HEIGHT // 2, 120, 40)
                quit_button = pygame.Rect(WIDTH // 2 - 60, HEIGHT // 2 + 60, 120, 40)
                if restart_button.collidepoint(mouse_pos):
                    reset()  # 重置游戏状态
                    game_state = "playing"
                elif quit_button.collidepoint(mouse_pos):
                    running = False

    if game_state == "playing" and not explosion_active:
        # 更新蛇的位置
        snake.move()

        # 更新AI蛇的位置
        ai_snake.move_towards_food([food.position for food in food_list])

        # 检查蛇是否吃到食物
        head = snake.body[0]
        food_to_eat = check_food_collision(head, [food.position for food in food_list])
        if food_to_eat:
            snake.grow()
            for food in food_list:
                if food.position == food_to_eat:
                    food.reset(snake.body, ai_snake.body)  # 传递蛇和AI蛇的身体位置
                    eat_sound.play()  # 播放吃到食物音效
                    break

        # 检查AI蛇是否吃到食物
        ai_head = ai_snake.body[0]
        food_to_eat = check_food_collision(ai_head, [food.position for food in food_list])
        if food_to_eat:
            ai_snake.grow()
            for food in food_list:
                if food.position == food_to_eat:
                    food.reset(snake.body, ai_snake.body)  # 传递蛇和AI蛇的身体位置
                    eat_sound.play()  # 播放吃到食物音效
                    break

        # 检查蛇是否撞到自己或墙壁
        if snake.check_collision(game_area_width, game_area_height):
            game_state = "game_over"
            explosion()

        # 检查AI蛇是否撞到自己或墙壁
        if ai_snake.check_collision(game_area_width, game_area_height):
            ai_snake.reset()
            explosion()
            ai_respawn_timer = AI_RESPAWN_TIME  # 设置AI蛇复活计时器

        # 处理AI蛇复活逻辑
        if ai_respawn_timer > 0:
            ai_respawn_timer -= 1
        elif ai_respawn_timer == 0:
            ai_snake = AISnake(game_area_width, game_area_height)  # 重置AI蛇的状态
            bgm.play(-1)  # 重新开始播放背景音乐

    # 更新粒子
    for particle in particles:
        particle.update()
    particles = [particle for particle in particles if particle.lifetime > 0]

    # 更新食物重生计时器
    update_food()

    # 绘制背景
    draw_background()

    if game_state == "playing" and not explosion_active:
        # 绘制蛇
        draw_snake()

        # 绘制AI蛇
        draw_ai_snake()

        # 绘制食物
        draw_food()
    elif explosion_active:
        # 绘制粒子
        draw_particles()
        explosion_timer += 1
        if explosion_timer > 30:  # 显示爆炸特效30帧后消失
            explosion_active = False
            explosion_timer = 0
    else:
        # 绘制游戏结束界面
        draw_game_over()

    # 绘制得分
    draw_score()

    # 更新屏幕显示
    pygame.display.flip()

    # 控制游戏帧率
    clock.tick(10)

# 退出游戏
pygame.quit()
sys.exit()